<?php
namespace app\common\model;
/**
 * 文档类型 - 文章
 */
class ArticleDoc extends BaseModel {

    protected $name = 'article_doc';

    protected $autoWriteTimestamp = true;

    public function add($data){
        try{
            //1添加基本数据
            $this->allowField(true)->save($data);
            //2添加关键字
            $tagIds = Tag::saveData($data['tags']);
            //3与关键字关联
            $batchData = [];
            foreach($tagIds as $v){
                $batchData[] = ['article_doc_id'=>$this->id , 'tag_id'=>$v];
            }
            $doctag = new ArticleDocTag();
            $doctag->saveAll($batchData);
            return true;
        }catch(Exception $e){
            $this->error = $e->getMessage();
            return false;
        }
    }

    public function edit($data){
        try{
            ArticleDocTag::where('article_doc_id' , $data['id'])->delete();
            unset($data['id']);
            //1编辑基本数据
            $this->allowField(true)->save($data);
            //2添加关键字
            $tagIds = Tag::saveData($data['tags']);
            //3与关键字关联
            $batchData = [];
            foreach($tagIds as $v){
                $batchData[] = ['article_doc_id'=>$this->id , 'tag_id'=>$v];
            }
            $doctag = new ArticleDocTag();
            $doctag->saveAll($batchData);
            return true;
        }catch(Exception $e){
            $this->error = $e->getMessage();
            return false;
        }
    }

    public function del(){
        try{
            ArticleDocTag::where('article_doc_id' , $this->id)->delete();
            $this->delete();
            return true;
        }catch(Exception $e){
            $this->error = $e->getMessage();
            return false;
        }
    }

    public function changeField($filed , $value){
        try{
            $this->$filed = $value;
            $this->save();
            return true;
        }catch(Exception $e){
            $this->error = $e->getMessage();
            return false;
        }
    }
}